﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;

namespace RapidTestMapMaker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            mapDisplayUserControl1.Enabled = false;
            palleteUserControl1.Enabled = false;
        }

        private TileSet DefaultTileSet()
        {
            String imgPath = Path.Combine(Application.StartupPath, "Textures");
            TileSet ts = new TileSet();
            ts.AddTile(LoadTile(Path.Combine(imgPath, "grass4.jpg")));
            ts.AddTile(LoadTile(Path.Combine(imgPath, "grass1.jpg")));
            ts.AddTile(LoadTile(Path.Combine(imgPath, "weeds1.jpg")));
            ts.AddTile(LoadTile(Path.Combine(imgPath, "cobble2.JPG")));
            ts.AddTile(LoadTile(Path.Combine(imgPath, "brick1.jpg")));
            ts.AddTile(LoadTile(Path.Combine(imgPath, "rock1.jpg")));
            ts.AddTile(LoadTile(Path.Combine(imgPath, "sand2.jpg")));
            ts.AddTile(LoadTile(Path.Combine(imgPath, "sand3.jpg")));
            ts.AddTile(LoadTile(Path.Combine(imgPath, "dirt1.jpg")));
            ts.AddTile(LoadTile(Path.Combine(imgPath, "leaves1.jpg")));
            return ts;
        }

        private Tile LoadTile(String imageFileName)
        {
            Tile result = new Tile();
            try
            {
                Bitmap temp = (Bitmap)Bitmap.FromFile(imageFileName);
                temp.SetResolution(96, 96);
                result.FullImage = temp;
            }
            catch (Exception e)
            {
                int a = 5;
            }
            return result;
        }

        private void changeMap(BigMap map, TileSet tileset = null)
        {
            TileSet temp = tileset ?? DefaultTileSet();
            this.map = map;
            this.tileset = temp;
            palleteUserControl1.TileSet = temp;
            mapDisplayUserControl1.TileSet = temp;
            mapDisplayUserControl1.Map = map;
            Refresh();
        }

        private TileSet tileset;
        private BigMap map;

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar))
            {
                int index = int.Parse("" + e.KeyChar) - 1;
                index = Math.Min(tileset.Tiles.Count, Math.Max(0, index));
                tileset.ActiveTile = tileset.Tiles[index];
            }
        }

        private void toolStripMenuItemNew_Click(object sender, EventArgs e)
        {
            changeMap(new BigMap(), DefaultTileSet());
        }

        private void toolStripMenuItemOpen_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "RTMM Map Files|*.rtmm;*.rtmmp";
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    using (FileStream fs = new FileStream(ofd.FileName, FileMode.Open))
                    {
                        var result = MapSerializer.Deserialize(fs, tileset);
                        changeMap(result.Map, result.TileSet);
                    }
                }
            }
        }

        private void toolStripMenuItemSave_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Filter = "Partial RTMM Map File|*.rtmmp|Complete RTMM Map File|*.rtmm";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create))
                    {
                        if (sfd.FileName.ToLowerInvariant().EndsWith("rtmmp"))
                        { MapSerializer.Serialize(map, tileset, false, fs); }
                        else
                        { MapSerializer.Serialize(map, tileset, true, fs); }
                    }
                }
            }
        }

        private void toolStripMenuItemLayers_Click(object sender, EventArgs e)
        {
            using (LayerDialog ld = new LayerDialog())
            {
                ld.ShowDialog();
            }
        }

        private void toolStripMenuItemExport_Click(object sender, EventArgs e)
        {
            String dest;
            using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Jpeg File|*.jpeg|Png File|*.png" })
            {
                if (sfd.ShowDialog() != DialogResult.OK)
                { return; }
                dest = sfd.FileName;
            }
            
            Rectangle rect = map.ImageBoundsIgnoringWalls;
            Size s = rect.Size;
            int xOffset = rect.Left;
            int yOffset = rect.Top;

            Bitmap output = new Bitmap(s.Width * tileset.TileWidth, s.Height * tileset.TileHeight);
            Graphics g = Graphics.FromImage(output);
            g.TranslateTransform(-xOffset * tileset.TileWidth, -yOffset * tileset.TileWidth);
            mapDisplayUserControl1.DrawMap(g, map, false);
            g.Flush();
            output.Save(dest, dest.ToLowerInvariant().EndsWith("png") ? ImageFormat.Png : ImageFormat.Jpeg);
        }

        private static FileInfo AutoSaveFile
        {
            get
            {
                FileInfo file = new FileInfo(Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "RapidTestMapMaker",
                "autosave.rtmmp"));
                if (!file.Directory.Exists)
                { file.Directory.Create(); }
                return file;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            using (FileStream fs = new FileStream(AutoSaveFile.FullName, FileMode.Create))
            {
                MapSerializer.Serialize(map, tileset, false, fs);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            TileSet defaultTileSet = DefaultTileSet();
            FileInfo autosave = AutoSaveFile;
            if (autosave.Exists)
            {
                using (FileStream fs = autosave.OpenRead())
                {
                    var autosavedMap = MapSerializer.Deserialize(fs, defaultTileSet);
                    changeMap(autosavedMap.Map, autosavedMap.TileSet);
                }
            }
            else
            { changeMap(new BigMap(), defaultTileSet); }
            mapDisplayUserControl1.Enabled = true;
            palleteUserControl1.Enabled = true;
        }

        private void floorsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            map.ActiveLayer = map.Layers[0];
            map.ActiveLayer.IsWall = false;
        }

        private void wallsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            map.ActiveLayer = map.Layers[1];
            map.ActiveLayer.IsWall = true;
        }
    }
}
